package com.cardmanager.pro.executor;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.cardmanager.pro.business.ConsumeTaskPOJOBusiness;
import com.cardmanager.pro.business.CreditCardAccountBusiness;
import com.cardmanager.pro.business.CreditCardAccountHistoryBusiness;
import com.cardmanager.pro.business.RepaymentTaskPOJOBusiness;
import com.cardmanager.pro.pojo.ConsumeTaskPOJO;
import com.cardmanager.pro.pojo.CreditCardAccount;
import com.cardmanager.pro.pojo.CreditCardAccountHistory;
import com.cardmanager.pro.pojo.RepaymentTaskPOJO;
import com.cardmanager.pro.util.CardConstss;
import com.cardmanager.pro.util.RestTemplateUtil;

import cn.jh.common.utils.CommonConstants;
import cn.jh.common.utils.DateUtil;
import cn.jh.common.utils.ExceptionUtil;
import net.sf.json.JSONObject;

@Component
@Scope("prototype")
public class ThreadRepaymentExecutor extends BaseExecutor implements Runnable {

	private final Logger LOG = LoggerFactory.getLogger(getClass());

	@Autowired
	private RepaymentTaskPOJOBusiness repaymentTaskPOJOBusiness;
	
	@Autowired
	private ConsumeTaskPOJOBusiness consumeTaskPOJOBusiness;

	@Autowired
	private CreditCardAccountBusiness creditCardAccountBusiness;
	
	
	@Autowired
	private CreditCardAccountHistoryBusiness creditCardAccountHistoryBusiness;
	
	@Autowired
	private RestTemplateUtil util;
	
	private RepaymentTaskPOJO repaymentTaskPOJO;
	
	private boolean isT1 = false;
	
	@Override
	public void run() {
		boolean isTrue = true;
		while (isTrue) {
			if (isTrue) {
				String userId = repaymentTaskPOJO.getUserId();
				String amount = repaymentTaskPOJO.getAmount().toString();
				String rate = repaymentTaskPOJO.getRate().toString();
				String orderCode = repaymentTaskPOJO.getOrderCode();
				String creditCardNumber = repaymentTaskPOJO.getCreditCardNumber();
				String description = repaymentTaskPOJO.getDescription();
				String version = repaymentTaskPOJO.getVersion();
				BigDecimal singleServiceCharge = repaymentTaskPOJO.getServiceCharge();
				String serviceCharge = repaymentTaskPOJO.getTotalServiceCharge().toString();
				String realAmount = repaymentTaskPOJO.getRealAmount().toString();
				String channelTag = repaymentTaskPOJO.getChannelTag();
				String repaymentTaskId = repaymentTaskPOJO.getRepaymentTaskId();
				
				CreditCardAccount creditCardAccount = creditCardAccountBusiness.findByUserIdAndCreditCardNumberAndVersion(userId, creditCardNumber,version);
				if(creditCardAccount != null){
					if(creditCardAccount.getBlance().compareTo(BigDecimal.ZERO) <= 0){
						this.failDealWith(new JSONObject(),"帐户余额为零,无法继续还款");
						isTrue = false;
						break;
					}
//					else{
//						realAmount = creditCardAccount.getBlance().toString();
//					}
				}
				
//				if(1 == repaymentTaskPOJO.getTaskType().intValue() && CardConstss.CARD_VERSION_1.equals(version)){
//					realAmount = new BigDecimal(realAmount).subtract(repaymentTaskPOJO.getServiceCharge()).toString();
//				}
				Random random = new Random();
				if(!"0".equals(orderCode)){
					orderCode = DateUtil.getDateStringConvert(new String(), new Date(),"yyyyMMddHHSSS")+random.nextInt(9)+random.nextInt(9)+random.nextInt(9)+random.nextInt(9)+"1";
				}else {
					orderCode = repaymentTaskId;
				}
				
				if (CardConstss.CARD_VERSION_6.equals(version)) {
					if (new BigDecimal(amount).compareTo(new BigDecimal(realAmount)) < 0) {
						realAmount = amount;
					}
				}
				
				repaymentTaskPOJO.setRealAmount(new BigDecimal(realAmount));
				
				if(!realAmount.equals(amount)){
					amount = realAmount;
				}
				
				if (CardConstss.CARD_VERSION_3.equals(version) || CardConstss.CARD_VERSION_5.equals(version)) {
					realAmount = new BigDecimal(realAmount).add(singleServiceCharge).toString();
				}
				
				JSONObject resultJSONObject;
				try {
					resultJSONObject = addCreditCardOrder(userId, rate, "11", amount, realAmount, creditCardNumber, channelTag, orderCode, serviceCharge, description, "");
				} catch (RuntimeException e) {
					e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
					this.errorDealWith(e);
					isTrue = false;
					break;
				}
				
				if(!CommonConstants.SUCCESS.equals(resultJSONObject.getString(CommonConstants.RESP_CODE))){
					LOG.error("=============="+orderCode+"==============还款任务生成订单失败:原因:"+(resultJSONObject.containsKey(CommonConstants.RESP_MESSAGE)?resultJSONObject.getString(CommonConstants.RESP_MESSAGE):"生成订单失败"));
					this.failDealWith(resultJSONObject,"原因:生成订单失败");
					isTrue = false;
					break;
				}
				
				if (CardConstss.CARD_VERSION_3.equals(version) || CardConstss.CARD_VERSION_5.equals(version)) {
					realAmount = new BigDecimal(realAmount).subtract(singleServiceCharge).toString();
				}
				
				repaymentTaskPOJO.setOrderCode(orderCode);
				
				try {
					resultJSONObject = getUserInfo(userId);
				} catch (RuntimeException e) {
					e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
					this.errorDealWith(e);
					isTrue = false;
					break; 
				}
				
				
				if(!CommonConstants.SUCCESS.equals(resultJSONObject.getString(CommonConstants.RESP_CODE))){
					LOG.error("=============="+orderCode+"==============还款任务获取用户信息失败:原因:"+(resultJSONObject.containsKey(CommonConstants.RESP_MESSAGE)?resultJSONObject.getString(CommonConstants.RESP_MESSAGE):"获取用户信息失败"));
					this.failDealWith(resultJSONObject,"原因:获取用户信息失败");
					isTrue = false;
					break;
				}
				resultJSONObject = resultJSONObject.getJSONObject(CommonConstants.RESULT);
				String brandcode = resultJSONObject.getString("brandId");
				
//				if (1 == repaymentTaskPOJO.getTaskType().intValue() && CardConstss.CARD_VERSION_1.equals(version)) {
//					repaymentTaskPOJO.setRealAmount(repaymentTaskPOJO.getRealAmount().add(repaymentTaskPOJO.getServiceCharge()));
//				}
				
				creditCardAccountBusiness.updateCreditCardAccountAndVersion(userId, creditCardNumber, repaymentTaskPOJO.getRepaymentTaskId(),1,repaymentTaskPOJO.getRealAmount(), description,repaymentTaskPOJO.getVersion());
			
				String extra = "0";
				if (CardConstss.CARD_VERSION_3.equals(version) || CardConstss.CARD_VERSION_5.equals(version)) {
					if (this.isT1Version3(creditCardAccount) || isT1) {
						extra = "T1";
					}
				}else if(CardConstss.CARD_VERSION_6.equals(version)){
					extra = "";
					List<ConsumeTaskPOJO> consumeTaskPOJOs = consumeTaskPOJOBusiness.findByRepaymentTaskId(repaymentTaskId);
					for (ConsumeTaskPOJO consumeTaskPOJO : consumeTaskPOJOs) {
						if (consumeTaskPOJO.getOrderStatus().intValue() == 1) {
							extra = extra + consumeTaskPOJO.getOrderCode() + ",";
						}
					}
					extra = extra.substring(0, extra.length()-1);
				}
				
				try {
					resultJSONObject = paymentTopupRequest(realAmount, orderCode, description, userId, brandcode, "0", channelTag,extra);
					LOG.info("======================================支付结果:" + resultJSONObject);
				} catch (RuntimeException e) {
					e.printStackTrace();
					ExceptionUtil.errInfo(e);
					repaymentTaskPOJO.setErrorMessage(e.toString().substring(0, e.toString().length()>=250?250:e.toString().length()));
					repaymentTaskPOJO.setTaskStatus(1);
					repaymentTaskPOJO.setOrderStatus(4);
					repaymentTaskPOJO.setReturnMessage("等待出款中,请稍后!");
					RepaymentTaskPOJO findByRepaymentTaskId = repaymentTaskPOJOBusiness.findByRepaymentTaskId(repaymentTaskPOJO.getRepaymentTaskId());
					if (findByRepaymentTaskId.getOrderStatus().intValue() == 1) {
						repaymentTaskPOJO.setOrderStatus(1);
						repaymentTaskPOJO.setReturnMessage("还款成功!");
					}
					repaymentTaskPOJOBusiness.save(repaymentTaskPOJO);
					isTrue = false;
					break;
				}
				
				
				
				if(!CommonConstants.SUCCESS.equals(resultJSONObject.getString(CommonConstants.RESP_CODE))){
					LOG.error("=============="+orderCode+"==============还款任务获取用户信息失败:原因:"+(resultJSONObject.containsKey(CommonConstants.RESP_MESSAGE)?resultJSONObject.getString(CommonConstants.RESP_MESSAGE):"支付失败"));
					if(CardConstss.WAIT_NOTIFY.equals(resultJSONObject.getString(CommonConstants.RESP_CODE))){
						repaymentTaskPOJO.setTaskStatus(1);
						repaymentTaskPOJO.setOrderStatus(4);
						repaymentTaskPOJO.setReturnMessage("等待出款中,请稍后!");
						RepaymentTaskPOJO findByRepaymentTaskId = repaymentTaskPOJOBusiness.findByRepaymentTaskId(repaymentTaskPOJO.getRepaymentTaskId());
						if (findByRepaymentTaskId.getOrderStatus().intValue() == 1) {
							repaymentTaskPOJO.setOrderStatus(1);
							repaymentTaskPOJO.setReturnMessage("还款成功!");
						}
						repaymentTaskPOJOBusiness.save(repaymentTaskPOJO);
					}else{
						creditCardAccountBusiness.updateCreditCardAccountAndVersion(userId, creditCardNumber,repaymentTaskPOJO.getRepaymentTaskId(), 3, repaymentTaskPOJO.getRealAmount(),"还款失败增加余额",repaymentTaskPOJO.getVersion());
						this.failDealWith(resultJSONObject,"原因:支付失败");
					}
					isTrue = false;
					break;
				}
				
				repaymentTaskPOJO.setReturnMessage("还款成功!");
				if(repaymentTaskPOJO.getAmount().compareTo(repaymentTaskPOJO.getRealAmount())!=0){
					repaymentTaskPOJO.setReturnMessage("还款成功,未还入预定金额!");
				}
				
				repaymentTaskPOJO.setTaskStatus(1);
				repaymentTaskPOJO.setOrderStatus(1);
				repaymentTaskPOJO.setRealAmount(new BigDecimal(realAmount));
				repaymentTaskPOJO = repaymentTaskPOJOBusiness.save(repaymentTaskPOJO);
				LOG.info("修改还款任务成功===================" + repaymentTaskPOJO);
				creditCardAccountBusiness.updateCreditCardAccountAndVersion(userId, creditCardNumber,repaymentTaskPOJO.getRepaymentTaskId(), 4, repaymentTaskPOJO.getRealAmount(), "还款成功减少冻结余额",repaymentTaskPOJO.getVersion());
				
				isTrue = false;
				break;
			}
		}

	}
	
	private void errorDealWith(Exception e){
//		if(repaymentTaskPOJO.getTaskType().intValue() != 1 && CardConstss.CARD_VERSION_1.equals(repaymentTaskPOJO.getVersion())){
//			repaymentTaskPOJO.setReturnServiceCharge(repaymentTaskPOJO.getReturnServiceCharge().add(repaymentTaskPOJO.getServiceCharge()));
//		}
//		if(repaymentTaskPOJO.getTaskType().intValue() != 1 && CardConstss.CARD_VERSION_1.equals(repaymentTaskPOJO.getVersion())){
//			creditCardAccountBusiness.updateCreditCardAccountAndVersion(repaymentTaskPOJO.getUserId(),repaymentTaskPOJO.getCreditCardNumber(), repaymentTaskPOJO.getRepaymentTaskId(),5,repaymentTaskPOJO.getServiceCharge(), "还款失败退还手续费",repaymentTaskPOJO.getVersion());
//		}
		repaymentTaskPOJO.setErrorMessage(e.toString().substring(0, e.toString().length()>=250?250:e.toString().length()));
		repaymentTaskPOJO.setTaskStatus(4);
		repaymentTaskPOJO.setRealAmount(BigDecimal.ZERO);
		repaymentTaskPOJO.setReturnMessage("还款失败!");
		repaymentTaskPOJOBusiness.save(repaymentTaskPOJO);
		util.pushMessage(repaymentTaskPOJO.getUserId(),"您有一笔金额为:"+repaymentTaskPOJO.getAmount()+"的还款任务失败,系统将在当天23:00前进行还款!");
	}
	
	private void failDealWith(JSONObject resultJSONObject,String message){
//		if(repaymentTaskPOJO.getTaskType().intValue() != 1 && CardConstss.CARD_VERSION_1.equals(repaymentTaskPOJO.getVersion())){
//			repaymentTaskPOJO.setReturnServiceCharge(repaymentTaskPOJO.getReturnServiceCharge().add(repaymentTaskPOJO.getServiceCharge()));
//		}
//		if(repaymentTaskPOJO.getTaskType().intValue() != 1 && CardConstss.CARD_VERSION_1.equals(repaymentTaskPOJO.getVersion())){
//			creditCardAccountBusiness.updateCreditCardAccountAndVersion(repaymentTaskPOJO.getUserId(), repaymentTaskPOJO.getCreditCardNumber(), repaymentTaskPOJO.getRepaymentTaskId(),5,repaymentTaskPOJO.getServiceCharge(), "还款失败退还手续费",repaymentTaskPOJO.getVersion());
//		}
		repaymentTaskPOJO.setErrorMessage(resultJSONObject.containsKey(CommonConstants.RESP_MESSAGE)?resultJSONObject.getString(CommonConstants.RESP_MESSAGE):message);
		repaymentTaskPOJO.setTaskStatus(2);
		repaymentTaskPOJO.setRealAmount(BigDecimal.ZERO);
		repaymentTaskPOJO.setReturnMessage(resultJSONObject.containsKey(CommonConstants.RESP_MESSAGE)?resultJSONObject.getString(CommonConstants.RESP_MESSAGE).replaceAll("[0-9]", "").replaceAll("[\\[|\\]|\\.|\\:]", "").replaceAll("[A-Za-z]", ""):message);
		repaymentTaskPOJOBusiness.save(repaymentTaskPOJO);
		util.pushMessage(repaymentTaskPOJO.getUserId(),"您有一笔金额为:"+repaymentTaskPOJO.getAmount()+"的还款任务失败,系统将在当天23:00前进行还款!");
	}

	public RepaymentTaskPOJO getRepaymentTaskPOJO() {
		return repaymentTaskPOJO;
	}

	public void setRepaymentTaskPOJO(RepaymentTaskPOJO repaymentTaskPOJO) {
		this.repaymentTaskPOJO = repaymentTaskPOJO;
	}

	
	/**
	 * 判断是否是T1出款
	 * @author Robin-QQ/WX:354476429 
	 * @date 2018年6月13日  
	 * @param creditCardAccount
	 * @return
	 */
	private boolean isT1Version3(CreditCardAccount creditCardAccount){
		boolean isTrue = false;
		List<CreditCardAccountHistory> creditCardAccountHistorys = creditCardAccountHistoryBusiness.findByCreditCardAccountIdAndAddOrSubOrderByCreateTimeDesc(creditCardAccount.getId(),0);
		if (creditCardAccountHistorys != null && creditCardAccountHistorys.size() > 0) {
			CreditCardAccountHistory creditCardAccountHistory = creditCardAccountHistorys.get(0);
			Date createTime = creditCardAccountHistory.getCreateTime();
			Calendar instance = Calendar.getInstance();
			instance.set(Calendar.HOUR_OF_DAY, 0);
			instance.set(Calendar.MINUTE, 0);
			if (createTime.compareTo(instance.getTime()) < 0) {
				isTrue = true;
			}
		}
		return isTrue;
	}

	public void setIsT1(boolean isT1) {
		this.isT1 = isT1;
	}
	
}
